package cn.angis.system.service;

import cn.angis.common.constant.Constant;
import cn.angis.common.util.TreeUtil;
import cn.angis.db.service.BaseService;
import cn.angis.system.dto.input.DeptInput;
import cn.angis.system.dto.input.LoginInput;
import cn.angis.system.dto.output.DeptOutput;
import cn.angis.system.dto.output.LoginOutput;
import cn.angis.system.mapper.DeptMapper;
import cn.angis.system.model.Dept;
import cn.angis.system.model.Roleres;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门表服务
 *
 * @author angis.cn
 * @Date 2023-01-05
 */
@Component
public class DeptService extends BaseService<DeptMapper, Dept> {
    public List<Dept> getTreeList() {
        String deptId = StpUtil.getSession().get(Constant.SESSION_DEPT_ID).toString();
        List<Dept> deptsList = baseMapper.createLambdaQuery()
                .andLike(Dept::getParentIds, "%" + deptId + "%")
                .select(Dept::getId, Dept::getCode, Dept::getParentId, Dept::getName, Dept::getParentIds);
        return TreeUtil.listToTree(deptsList);
    }

    public String getDeptIdByCode(String code) {
        List<Dept> deptList = baseMapper.createLambdaQuery()
                .andEq(Dept::getCode, code)
                .select(Dept::getId);
        String id = null;
        if (deptList != null && deptList.size() == 1) {
            id = deptList.get(0).getId();
        }
        return id;
    }


    public String getParentCode(String parentId) {
        return baseMapper.createLambdaQuery()
                .andEq(Dept::getId, parentId)
                .singleSimple().getCode();
    }

    public String getMaxCode(String parentId) {
        List<String> stringList = baseMapper.createLambdaQuery()
                .andEq(Dept::getParentId, parentId)
                .select(Dept::getParentIds)
                .stream().map(Dept::getParentIds)
                .collect(Collectors.toList());
        return Collections.max(stringList);
    }

    public List<DeptOutput> selectDeptList(DeptInput deptInput) {
        return baseMapper.selectDeptList(deptInput);
    }

}